const createError = require('http-errors')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
const cors = require('cors')
const dotenv = require('dotenv')
dotenv.config()
require('express-async-errors')

const routes = require('./routes')
const app = express()

const passport = require('passport')
require('./config/passport')(passport)

app.use(cors())
app.use(passport.initialize())
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use('/public', express.static(path.join(__dirname, 'config/data/upload')))

// 请求favicon.ico 不知道这种处理方式对不对,暂时这样处理
app.get('/favicon.ico', (req, res) => {
  res.redirect('http://localhost:8087/public/ico/atom.ico')
})

// 处理options请求
app.options('*', async (req, res) => {
  res.send('success')
})

// 所有路由
app.use('/api', routes)
// app.use('/new', require('./new/index.route'))
// const mongoose = require('mongoose')
// mongoose.set('debug', true)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  res.status(err.status || 500)
  res.json({ message: err.message, code: err.code || 20004 })
  next(err)
})

module.exports = app
